package middleware

import (
	"fmt"
	"game-server/config"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

// WSAuthMiddleware WebSocket连接的认证中间件
func WSAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从URL参数获取token
		token := c.Query("token")
		if token == "" {
			// 尝试从Authorization头获取token
			authHeader := c.GetHeader("Authorization")
			if authHeader == "" {
				c.JSON(401, gin.H{"error": "未提供认证token"})
				c.Abort()
				return
			}
			// 解析Bearer token
			parts := strings.Split(authHeader, " ")
			if len(parts) != 2 || parts[0] != "Bearer" {
				c.JSON(401, gin.H{"error": "认证格式错误"})
				c.Abort()
				return
			}
			token = parts[1]
		}

		// 验证token
		parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
			// 验证签名方法
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("意外的签名方法: %v", token.Header["alg"])
			}
			return []byte(config.GlobalConfig.JWT.Secret), nil
		})

		if err != nil {
			c.JSON(401, gin.H{"error": "无效的token"})
			c.Abort()
			return
		}

		// 验证token中的声明
		if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
			// 将claims存储到上下文中
			c.Set("claims", claims)
			c.Next()
			return
		}

		c.JSON(401, gin.H{"error": "无效的token声明"})
		c.Abort()
	}
}
